/*
OTA升级网页
使用此方法前需要创建webserver
WebServer update_server(server_port);
*/

//登录界面
String loginIndex(String suffix){
      return  "<html><head><meta charset='utf-8'><title>登录</title></head><body>"
              "<form name='login' method='Post' action='/serverIndex" +suffix+ "'>"
                "<table width='20%' bgcolor='A09F9F' align='center'>"
                  "<tr>"
                    "<td colspan=2>"
                      "<center><font size=4><b>登录页面</b></font></center>"
                      "<br>"
                    "</td>"
                    "<br>"
                    "<br>"
                  "</tr>"
                  "<tr>"
                    "<td align='right'>用户:</td>"
                    "<td align='center'><input type='text' size=25 name='userid' id='userid'><br></td>"
                  "</tr>"
                  "<br>"
                  "<br>"
                  "<tr>"
                    "<td align='right'>密码:</td>"
                    "<td align='center'><input type='Password' size=25 name='pwd' id='pwd'><br></td>"
                    "<br>"
                    "<br>"
                  "</tr>"
                  "<tr>"
                    "<td colspan=2><center><input type='submit' name='Login' id='Login'></center></td>"
                  "</tr>"
                "</table>"
                "</form>"
            "</body></html>";
}

//升级界面
String serverIndex(String suffix){
    return  "<html><head><meta charset=\"utf-8\"><title>上传固件</title></head><body>"
            "<script src='https://code.jquery.com/jquery-3.7.0.min.js'></script>"
            "<form method='POST' action='#' enctype='multipart/form-data' id='upload_form' name='upload_form'>"
              "<input type='file' name='update'>"
              "<input type='submit' value='上传'>"
            "</form><br>"
            "<div id='prg'>进度: 0%</div>"
            "<script>"
              "$('form').submit(function(e){"
              "e.preventDefault();"
              "var form = $('#upload_form')[0];"
              "var data = new FormData(form);"
              " $.ajax({"
              "url: '/update" +suffix+ "',"
              "type: 'POST',"
              "data: data,"
              "contentType: false,"
              "processData:false,"
              "xhr: function() {"
              "var xhr = new window.XMLHttpRequest();"
              "xhr.upload.addEventListener('progress', function(evt) {"
              "if (evt.lengthComputable) {"
              "var per = evt.loaded / evt.total;"
              "$('#prg').html('进度: ' + Math.round(per*100) + '%');"
              "}"
              "}, false);"
              "return xhr;"
              "},"
              "success:function(d, s) {"
              "console.log('success!')"
            "},"
            "error: function (a, b, c) {"
            "}"
            "});"
            "});"
            "</script></body></html>";
}

void update_server_start(){
  //开启MDNS
  if(ota_resetup_millis!=0 && ota_resetup_millis<2000){return;}   //ota开户失败后等待2s再重新连接
  if(!MDNS.begin(wifi_host.c_str())){
    Serial.println(F("mDNS启动失败,2s后重新尝试!"));
    ota_resetup_millis = millis();
    return;
  }
  Serial.println(F("mDNS启动成功!"));
  ota_resetup_millis = 0;
  //启用web登录上传页面
  update_server.on("/", HTTP_GET, []() {
    sys_ota_add_suffix = String(random(100000, 999999));
    update_server.sendHeader("Connection", "close");
    update_server.send(200, "text/html", loginIndex(sys_ota_add_suffix));
    //上传界面
    update_server.on("/serverIndex" + sys_ota_add_suffix, HTTP_POST, []() {
    if(update_server.hasArg("userid")){
      if(update_server.arg("userid")==system_ota_usr && update_server.arg("pwd")==system_ota_psd){
        update_server.sendHeader("Connection", "close");
        update_server.send(200, "text/html", serverIndex(sys_ota_add_suffix));
      }else{
        update_server.send(200, "text/html", loginIndex(sys_ota_add_suffix));
      }
    }
    //启用web上传服务
    update_server.on("/update" + sys_ota_add_suffix, HTTP_POST, []() {
      update_server.sendHeader("Connection", "close");
      update_server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
      store_sys_data(); //保存数据到EEPROM
      ESP.restart();
      }, []() {
        //固件升级功能
          HTTPUpload& upload = update_server.upload();
          if (upload.status == UPLOAD_FILE_START) {
            Serial.printf("Update: %s\n", upload.filename.c_str());
            if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
              Update.printError(Serial);
            }
          } else if (upload.status == UPLOAD_FILE_WRITE) {
            // flashing firmware to ESP
            if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
              Update.printError(Serial);
            }
          } else if (upload.status == UPLOAD_FILE_END) {
            if (Update.end(true)) { //true to set the size to the current progress
              Serial.printf("固件上传成功: %u\n更新并重启...\n", upload.totalSize);
            } else {
              Update.printError(Serial);
            }
          }
      });
    });
  });
  //启动升级服务
  update_server.begin();
  system_ota_initialized = 1;
}
//OTA功能初始化
void OTA_setup(){
  if(system_internet_mode!=0 && system_enable_OTA==1){
    update_server_start();
  }
}
